import { inject, computed, watch, ref, onUnmounted } from 'vue';

function usePreview(src, options) {
  // 从上下文获取核心方法
  const imageContext = inject('ImageContext', {
    enable: ref(false),
    defaultReader: '',
    readerOption: {},
    register: () => {},
    open: () => {},
    go: () => {},
  });

  // 响应式注册器引用
  const unRef = ref({});

  // 计算预览地址
  const previewSrc = computed(() => {
    const reader = imageContext.readerOption[options?.reader || imageContext.defaultReader] || options?.reader;
    return reader?.preview?.(src) || src;
  });

  // 注册/更新预览项
  const registerPreview = () => {
    if (!imageContext.enable) return;
    unRef.value.remove?.();
    unRef.value = imageContext.register(options?.group, previewSrc?.value);
  };

  // 自动清理机制
  onUnmounted(() => unRef.value.remove?.());
  watch(previewSrc, registerPreview, { immediate: true });

  // 打开预览方法
  const openPreview = () => {
    const { group, index } = unRef.value;
    imageContext.open(group, index);
  };

  return { previewSrc, open: openPreview };
}

export default usePreview;
